package com.easyjob.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easyjob.annotation.GlobalInterceptor;
import com.easyjob.annotation.VerifyParam;
import com.easyjob.entity.dto.AppUserLoginDto;
import com.easyjob.entity.dto.ExamConfigDto;
import com.easyjob.entity.dto.TimeDto;
import com.easyjob.entity.dto.TimeInfo;
import com.easyjob.entity.enums.AppExamStatusEnum;
import com.easyjob.entity.enums.ResponseCodeEnum;
import com.easyjob.entity.po.AppExam;
import com.easyjob.entity.query.AppExamQuery;
import com.easyjob.entity.query.AppExamQuestionQuery;
import com.easyjob.entity.vo.ExamInfoVo;
import com.easyjob.entity.vo.ResponseVO;
import com.easyjob.entity.vo.app.AppExamVO;
import com.easyjob.entity.vo.app.ExamQuestionVO;
import com.easyjob.exception.BusinessException;
import com.easyjob.mappers.plus.AppExamMapperPlus;
import com.easyjob.service.AppExamService;
import com.easyjob.utils.BeanCopyUtils;
import com.easyjob.utils.DateUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 问题 Controller
 */
@RestController("appExamController")
@RequestMapping("/appExam")
public class AppExamController extends ABaseController {

    @Resource
    private AppExamService appExamService;

    @Resource
    private AppExamMapperPlus appExamMapperPlus;

    @RequestMapping("/loadNoFinishedExam")
    @GlobalInterceptor
    public ResponseVO loadNoFinishedExam(@RequestHeader(value = "token", required = false) String token) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        if (appDto == null) {
            return getSuccessResponseVO(null);
        }
        AppExamQuery appExamQuery = new AppExamQuery();
        appExamQuery.setStatus(AppExamStatusEnum.INIT.getStatus());
        appExamQuery.setUserId(appDto.getUserId());
        appExamQuery.setOrderBy("exam_id desc");
        List<AppExam> appExamList = appExamService.findListByParam(appExamQuery);
        return getSuccessResponseVO(appExamList);
    }
    @RequestMapping("/loadHistoryExamById")
    @GlobalInterceptor
    public ResponseVO loadHistoryExamById(@RequestHeader(value = "token", required = true) String token,
                                          @RequestParam("id") Integer examId) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        if (appDto == null) {
            return getSuccessResponseVO(null);
        }
        JSONObject data = appExamService.loadHistoryById(examId, appDto);
        return getSuccessResponseVO(data);
    }

    @RequestMapping("/loadHistoryExam")
    @GlobalInterceptor
    public ResponseVO loadHistoryExam(@RequestHeader(value = "token", required = false) String token) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        if (appDto == null) {
            return getSuccessResponseVO(null);
        }
        LambdaQueryWrapper<AppExam> query = new LambdaQueryWrapper<>();
        query.eq(AppExam::getUserId, appDto.getUserId());
        query.orderByAsc(AppExam::getCreateTime);
        Map<String, List<TimeInfo>> hash = new HashMap<>(1 << 12);
        List<AppExam> appExams = appExamMapperPlus.selectList(query);
        for (AppExam item : appExams) {
            String[] s= DateUtil.fromDate2String(item.getStartTime()).split(" ");
            String key = s[0];
            TimeInfo timeInfo = new TimeInfo();
            timeInfo.setStartTime(DateUtil.fromDate2String(item.getStartTime()).split(" ")[1]);
            if (item.getEndTime() != null) {
                timeInfo.setEndTime(DateUtil.fromDate2String(item.getEndTime()).split(" ")[1]);
            }
            timeInfo.setScore(item.getScore());
            timeInfo.setStatus(item.getStatus());
            timeInfo.setExamId(item.getExamId());
            if (hash.containsKey(key)) {
                hash.get(key).add(timeInfo);
            } else {
                List<TimeInfo> arr = new ArrayList<>();
                arr.add(timeInfo);
                hash.put(key, arr);
            }
        }
        List<TimeDto> timeDtoList = hash.keySet().stream().map(key -> {
            TimeDto timeDto = new TimeDto();
            timeDto.setTime(key);
            timeDto.setChildren(hash.get(key));
            return timeDto;
        }).
                sorted(Comparator.comparing(TimeDto::getTime)).
                collect(Collectors.toList());
        return getSuccessResponseVO(timeDtoList);
    }

    /**
     * 根据条件分页查询
     */
    @RequestMapping("/createExam")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO createExam(@RequestHeader(value = "token", required = false) String token,
                                 @RequestBody ExamConfigDto examConfigDto) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        JSONObject object = appExamService.createExam(examConfigDto, appDto);
        return getSuccessResponseVO(object);
    }

    @RequestMapping("/getExamQuestion")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO getExamQuestion(@RequestHeader(value = "token", required = false) String token,
                                      @VerifyParam(required = true) Integer examId) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        checkAppExam(appDto, examId);
        AppExam appExam = checkAppExam(appDto, examId);
        Boolean showAnswer = false;
        if (AppExamStatusEnum.FINISHED.getStatus().equals(appExam.getStatus())) {
            showAnswer = true;
        }
        AppExamVO appExamVO = BeanCopyUtils.copyBean(appExam, AppExamVO.class);
        AppExamQuestionQuery appExamQuestionQuery = new AppExamQuestionQuery();
        appExamQuestionQuery.setExamId(examId);
        appExamQuestionQuery.setUserId(appDto.getUserId());
        appExamQuestionQuery.setShowUserAnswer(showAnswer);
        List<ExamQuestionVO> examQuestionList = appExamService.getAppExamQuestion(appExamQuestionQuery);
        for (ExamQuestionVO item : examQuestionList) {
            item.setQuestion(resetContentImg(item.getQuestion()));
            item.setAnswerAnalysis(resetContentImg(item.getAnswerAnalysis()));
        }
        appExamVO.setExamQuestionList(examQuestionList);
        return getSuccessResponseVO(appExamVO);
    }

    @RequestMapping("/startExam")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO startExam(@RequestHeader(value = "token", required = false) String token,
                                @VerifyParam(required = true) Integer examId) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        checkAppExam(appDto, examId);
        Date curDate = new Date();
        AppExam appExam = new AppExam();
        appExam.setStartTime(curDate);
        AppExamQuery appExamQuery = new AppExamQuery();
        appExamQuery.setExamId(examId);
        appExamQuery.setUserId(appDto.getUserId());
        appExamService.updateByParam(appExam, appExamQuery);
        return getSuccessResponseVO(curDate);
    }

    @RequestMapping("/delExam")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO delExam(@RequestHeader(value = "token", required = false) String token,
                              @VerifyParam(required = true) Integer examId) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        checkAppExam(appDto, examId);
        appExamService.delExam4Api(appDto.getUserId(), examId);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/postExam")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO postExam(@RequestHeader(value = "token", required = false) String token,
                               @RequestBody ExamInfoVo appExamPostVo) {
        AppUserLoginDto appDto = getAppUserLoginInfoFromToken(token);
        AppExam appExam = appExamService.postExam(appDto, appExamPostVo);
        return getSuccessResponseVO(appExam);
    }

    private AppExam checkAppExam(AppUserLoginDto appDto, Integer examId) {
        AppExam appExam = appExamService.getAppExamByExamId(examId);
        if (null == appExam || !appDto.getUserId().equals(appExam.getUserId())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        return appExam;
    }
}